import json
import requests
from flask import Flask, request, jsonify
from flask_cors import CORS

app = Flask(__name__)
CORS(app)  # 启用CORS，允许所有域名访问

# 配置讯飞API密钥
API_KEY = "Bearer HreEJANqlzHpNrYSceGh:YadMASikQquFBxxiIHem"  # 替换为您的实际密钥
API_URL = "https://spark-api-open.xf-yun.com/v2/chat/completions"

@app.route('/generate_paper', methods=['POST'])
def generate_paper():
    # 获取前端传来的试卷参数
    data = request.json
    
    # 构建请求体
    headers = {
        'Authorization': API_KEY,
        'Content-Type': 'application/json'
    }
    
    body = {
        "model": "x1",
        "user": "grade3_teacher",
        "messages": data['messages'],
        "stream": True,
        "tools": [{"type": "web_search", "web_search": {"enable": False}}]
    }
    
    try:
        # 调用讯飞API
        response = requests.post(
            url=API_URL,
            json=body,
            headers=headers,
            stream=True,
            timeout=60
        )
        
        if not response.ok:
            return jsonify({"error": f"API调用失败: HTTP {response.status_code}"})
        
        # 处理响应并返回给前端
        full_content = ""
        for chunk in response.iter_lines():
            if chunk and b'[DONE]' not in chunk:
                data_str = chunk[6:].decode('utf-8')
                try:
                    data_json = json.loads(data_str)
                    if 'choices' in data_json and data_json['choices']:
                        delta = data_json['choices'][0]['delta']
                        if 'content' in delta:
                            full_content += delta['content']
                except:
                    continue
        
        return jsonify({"success": True, "content": full_content})
    except Exception as e:
        return jsonify({"error": str(e)})

if __name__ == '__main__':
    # 注意：生产环境不要使用debug=True
    app.run(host='127.0.0.1', port=5000, debug=True)